#ifndef XTIMER_HPP
#define XTIMER_HPP
#include "signal.hpp"
#include<thread>
#include<chrono>

class xtimer:public SIG::sigReciver{
public:
    xtimer(){}

    ~xtimer(){
        stop(); //停止定时器线程
    }

    void start(unsigned int msec){
        if(m_thrd.joinable()){
            //定时器已启动
            return;
        }
        m_msec = msec;
        m_thrd = std::thread([this](){
            while (this->m_runFlag)
            {
                std::this_thread::sleep_for(std::chrono::milliseconds(this->m_msec));
                xemit(sinTimeout)();
            }
        });
    }

    void stop(){
        m_runFlag = false;
        if(m_thrd.joinable())
            m_thrd.join();  //停止内部线程
    }

private:
    unsigned int m_msec;          //定时器间隔
    std::thread m_thrd;             //线程定时发射定时信号
    bool m_runFlag = true;    
public:     
    XSIGNAL(sinTimeout);                      //定时器触发信号
};
#endif